package com.djl.zenithbite.service.shopping.impl;

import com.djl.zenithbite.common.response.BaseResponse;
import com.djl.zenithbite.common.response.PageQueryResponse;
import com.djl.zenithbite.common.threadlocal.UserContextHolder;
import com.djl.zenithbite.dto.request.shopping.ShoppingQueryRequest;
import com.djl.zenithbite.dto.vo.ShoppingQueryVO;
import com.djl.zenithbite.entity.OrderExample;
import com.djl.zenithbite.entity.Product;
import com.djl.zenithbite.entity.Store;
import com.djl.zenithbite.entity.User;
import com.djl.zenithbite.repository.OrderMapper;
import com.djl.zenithbite.repository.ProductMapper;
import com.djl.zenithbite.repository.impl.ProductRepositoryImpl;
import com.djl.zenithbite.repository.impl.StoreRepositoryImpl;
import com.djl.zenithbite.service.shopping.ShoppingService;
import com.djl.zenithbite.service.user.UserProductQueryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ShoppingServiceImpl implements ShoppingService {

    @Autowired
    private ProductRepositoryImpl productRepository;

    @Autowired
    private StoreRepositoryImpl storeRepository;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserProductQueryService userProductQueryService;

    @Override
    public BaseResponse list(ShoppingQueryRequest request) {
        User user = UserContextHolder.getUser();
        if (user == null){
            return queryProductWhenUserNotLogin(request);
        }else {
            return queryProductWhenUserLogin(request);
        }
    }

    private BaseResponse queryProductWhenUserNotLogin(ShoppingQueryRequest request){

        List<ShoppingQueryVO>  shoppingQueryVOList = new ArrayList<>();

        PageQueryResponse<List<ShoppingQueryVO>> response = new PageQueryResponse<>();


        //Page<Object> page = PageHelper.startPage(request.getPageStart(), request.getPageSize());
        List<Product> products = productRepository.queryProduct(request);

        buildProduct(products, response);

        return response;

    }

    private void buildProduct(List<Product> products, PageQueryResponse<List<ShoppingQueryVO>> response) {
        if (!CollectionUtils.isEmpty(products)){
            Map<Integer, Store> storeMap = products.stream()
                    .map(Product::getStoreId)
                    .distinct()
                    .map(storeId -> storeRepository.queryById(storeId))
                    .collect(Collectors.toMap(Store::getStoreId, Function.identity()));

            Map<Integer, List<Product>> map = products.stream()
                    .collect(Collectors.groupingBy(Product::getStoreId));

            Map<Integer,Boolean> flagMap = new HashMap<>();

            List<ShoppingQueryVO> shoppingQueryVOS = products.stream().map(product -> {
                if (flagMap.get(product.getStoreId()) != null) {
                    return null;
                }
                flagMap.put(product.getStoreId(), true);
                Store store = storeMap.get(product.getStoreId());
                Integer storeId = store.getStoreId();
                OrderExample orderExample = new OrderExample();
                OrderExample.Criteria criteria = orderExample.createCriteria();
                criteria.andStoreIdEqualTo(storeId);

                int count = orderMapper.countByExample(orderExample);

                ShoppingQueryVO shoppingQueryVO = new ShoppingQueryVO();
                shoppingQueryVO.setProductList(map.get(product.getStoreId()));
                shoppingQueryVO.setStore(store);
                shoppingQueryVO.setSalesCount(count);

                return shoppingQueryVO;
            }).filter(Objects::nonNull).collect(Collectors.toList());


           /* List<ShoppingQueryVO> shoppingQueryVOS = map.entrySet().stream().map(entry -> {

                Store store = storeMap.get(entry.getKey());
                Integer storeId = store.getStoreId();
                OrderExample orderExample = new OrderExample();
                OrderExample.Criteria criteria = orderExample.createCriteria();
                criteria.andStoreIdEqualTo(storeId);

                int count = orderMapper.countByExample(orderExample);

                ShoppingQueryVO shoppingQueryVO = new ShoppingQueryVO();
                shoppingQueryVO.setProductList(entry.getValue());
                shoppingQueryVO.setStore(store);
                shoppingQueryVO.setSalesCount(count);

                return shoppingQueryVO;
            }).collect(Collectors.toList());*/

            response.setData(shoppingQueryVOS);
            response.setCode(BaseResponse.SUCCESS);
            //response.setTotal(page.getTotal());
        }
    }

    private BaseResponse queryProductWhenUserLogin(ShoppingQueryRequest request){
        List<ShoppingQueryVO>  shoppingQueryVOList = new ArrayList<>();

        PageQueryResponse<List<ShoppingQueryVO>> response = new PageQueryResponse<>();
        List<Product> products  = null;
        if (StringUtils.isNotBlank(request.getProductName())){
           products  = productRepository.queryProduct(request);
        }else {
            products = userProductQueryService.storeList();
        }

        buildProduct(products,response);

        return response;
    }
}
